# 对所有二维地图服务进行管理
import os
import json

from src.formats.ZIP.ZipManager import ZipManager
from src.formats.ESRITpk.ESRITpkManager import ESRITpkManager
from src.formats.MBTTiles.MBTTilesManager import MBTTilesManager
from src.formats.ESRISlpk.ESRISlpkManager import ESRISlpkManager
from src.formats.C3DTiles.C3DTilesManager import C3DTilesManager
from src.formats.ESRIBundle.ESRIBundleManager import BundleBundlxManager
from src.formats.ReadMapServiceConfig import ReadMapServiceConfig
from src.formats.PathManager import PathManager


def getSrcPath():
    return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  # 返回引用模块的绝对路径 D:\tilemap\tilemap_pkg_services\src
    # list = os.listdir('src/services')
class MapServiceManager:
    def __init__(self):
        self.srcPath = getSrcPath()
        # docker
        # self.configPath = '/opt/tilemapservices'

        # 设置配置文件目录
        # 若未指定参数，则使用默认参数
        # if len(sys.argv) != 2:
        #     print('未指定服务配置文件路径,系统即将退出. . .')
        #     sys.exit(-1)
        # self.configPath = self.srcPath + '/services'
        # else:
        #     self.configPath = sys.argv[1]
        self.readConfig = ReadMapServiceConfig()

        # 所有服务的列表
        self.serviceList = {}
        self.MapServerJSON = self.readMapServer() # src/conf/MapServer.json文件

    # 直接对配置文件目录进行递归扫描，依次添加所有可用配置文件，主要依据配置文件后缀名进行判别
    def readServerConfigFiles(self, path):
        try:
            dirs = os.listdir(path)
            for i in dirs:
                if os.path.isfile(path + '/' + i):
                    # ns = ns + 1
                    try:
                        self.readAndAddServer(path + '/' + i)
                    except Exception as e:
                        print(e)
                        print('初始化读取服务配置文件:' + path + '/' + i + '时出错')

                    # print('stop' + path + '/' + i)
                elif os.path.isdir(path + '/' + i):
                    # print('folder' + path + '/' + i)
                    self.readServerConfigFiles(path + '/' + i)

            # print(self.serviceList)
        except Exception as e:
            print(e)
            print('初始化读取服务配置文件:' + path + '时出错')

    # 从服务配置文件清单中获取配置文件地址进行读取
    def readServerConfigFiles_fromCF(self):
        # 获取所有的key
        sections = self.readConfig.getAll()
        for i in sections:
            # services/.tpkinfo  .slpkinfo
            self.readAndAddServer(self.readConfig.getParameter(i))

    def readServerConfigFiles_fromDB(self):
        print('从数据库中读取配置文件得路径信息并进行添加')

    def readAndAddServer(self, i):
        fileType = os.path.splitext(i)[1]
        path = i
        targetFileType = ['.tpkinfo', '.mbtinfo', '.c3dtinfo', '.slpkinfo', '.zipinfo','.bundleinfo']

        if fileType in targetFileType:
            try:
                with open(path, encoding='utf-8') as f:
                    obj = json.load(f)
                    serviceName = obj['serviceName']
                    self.serviceList[serviceName] = {}
                    self.serviceList[serviceName]['config'] = obj

                    # 修正pkgPath
                    path_temp = path[:path.rfind('/')]
                    self.serviceList[serviceName]['config']['pkgPath'] = PathManager.pathJoin(path_temp,self.serviceList[serviceName]['config']['pkgPath'])

                    if fileType == '.tpkinfo':
                        # obj = f.read()
                        # obj = json.load(f)
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'tpk':
                            self.serviceList[serviceName]['tilesManager'] = ESRITpkManager(obj['pkgPath'])
                            # 读取mapserver
                            if 'MapServerJSONPath' in self.serviceList[serviceName]['config']:
                                # 修正Path
                                path_temp = path[:path.rfind('/')]
                                self.serviceList[serviceName]['config']['MapServerJSONPath'] = PathManager.pathJoin(path_temp, self.serviceList[serviceName]['config']['MapServerJSONPath'])
                                self.serviceList[serviceName]['config']['MapServerJSON'] = self.readMapServer_FromConfig(self.serviceList[serviceName]['config']['MapServerJSONPath'])

                    elif fileType == '.mbtinfo':
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'mbt':
                            self.serviceList[serviceName]['tilesManager'] = MBTTilesManager(obj['pkgPath'])

                    elif fileType == '.bundleinfo':
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'bundle':
                            self.serviceList[serviceName]['tilesManager'] = BundleBundlxManager(obj['pkgPath'])

                    elif fileType == '.slpkinfo':
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'slpk':
                            self.serviceList[serviceName]['tilesManager'] = ESRISlpkManager(obj['pkgPath'])

                    elif fileType == '.c3dtinfo':
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'c3dtiles':
                            self.serviceList[serviceName]['tilesManager'] = C3DTilesManager(obj['pkgPath'])\

                    elif fileType == '.zipinfo':
                        print(obj['cnName'])
                        # 针对不同的文件类型进行初始化
                        if self.serviceList[serviceName]['config']['type'] == 'zip':
                            self.serviceList[serviceName]['tilesManager'] = ZipManager(obj['pkgPath'])

            except Exception as e:
                print(e)
                print('读取服务配置文件时出错')

    def readMapServer(self):
        path = self.srcPath + '/conf/MapServer.json'
        with open(path, encoding='utf-8') as f:
            # obj = json.loads(f.read(), object_pairs_hook=OrderedDict)
            obj = f.read()
            return obj

    # 从配置文件中得路径读取MapServer文件
    def readMapServer_FromConfig(self, path):
        with open(path, encoding='utf-8') as f:
            # obj = json.loads(f.read(), object_pairs_hook=OrderedDict)
            obj = f.read()
            return obj


# 之下两行不能删除，将会在程序运行期间提供全局对象
mapServiceManager = MapServiceManager()
# mapServiceManager.readServerConfigFiles(mapServiceManager.configPath)
mapServiceManager.readServerConfigFiles_fromCF()
# print(type(mapServiceManager.MapServerJSON))


